import React, { useState } from 'react';
import styles from './index.less';
import { Tabs, Table, Spin, Drawer } from 'antd';
import { tableLocale } from '@/tool/components/PageEmpty';
import moment from 'moment';
import { connect } from 'umi';

import { TRMessage } from '#/components';
import { HttpCode } from '#/utils/contacts';
import { operateLogModal, selectedCircle, upHide, downShow } from '@/assets';
import { TradeStrategy, SubmitType } from '@/pages/Tianji/TenDaysCentralizedBidding/constant';
import { fetchOperateLogs, fetchPrograms } from '@/pages/Tianji/TenDaysCentralizedBidding/services';
import { DownSquareOutlined, UpSquareOutlined } from '@ant-design/icons';

const { Column } = Table;
const { TabPane } = Tabs;

const operateLogType = {
  0: '新增方案',
  1: '删除方案',
  2: '修改方案内容',
  3: '修改方案交易单元',
  4: '提请立即申报',
  5: '申报成功',
  6: '申报部分成功',
  7: '设置定时申报',
  8: '定时申报',
  9: '取消定时申报',
  10: '申报失败',
};

function SDItemContent({ item, index }) {
  switch (item.type) {
    case 1:
    case 5:
    case 10:
      break;
    case 0:
    case 2:
    case 4:
    case 8:
      return (
        <Table
          className={styles.table}
          dataSource={item.hourOrderInfos}
          rowKey="hourOrder"
          bordered={true}
          pagination={false}
          locale={tableLocale}
        >
          <Column title="日期" align="center" dataIndex="date" key="date" />
          <Column
            align="center"
            title="交易方向"
            dataIndex="tradeStrategy"
            key="tradeStrategy"
            render={(text) => {
              switch (text) {
                case TradeStrategy.SELL:
                  return <span>卖出</span>;
                case TradeStrategy.BUY:
                  return <span>买入</span>;
                case TradeStrategy.NOT_DEAL:
                  return <span>不交易</span>;
                case TradeStrategy.NO_STRATEGY:
                  return <span>无策略</span>;
              }
            }}
          />
          <Column
            align="center"
            title="申报电量"
            dataIndex="firstSubmitPower"
            key="firstSubmitPower"
            render={(text, record) => {
              switch (record.submitType) {
                case SubmitType.FIXED:
                  return <>{text.toFixed(3)}MWh</>;
                case SubmitType.INSTALLED_CAPACITY:
                  return <>装机容量*{Math.round(text * 100)}%</>;
                case SubmitType.TRADE_LIMIT:
                  return <>交易限额*{Math.round(text * 100)}%</>;
              }
            }}
          />
          <Column
            align="center"
            title="申报电价"
            dataIndex="firstPrice"
            key="firstPrice"
            render={(text) => <>{text.toFixed(2)}元/MWh</>}
          />
        </Table>
      );
    case 3:
      return <>{item.units.join('、')}</>;
    case 6:
      return (
        <>
          <div className={styles.successUnits}>
            <span className={styles.label}>成功{item.successUnits.length}</span>
            <span className={styles.list}>{item.successUnits.join('、')}</span>
          </div>
          <div className={styles.failUnits}>
            <span className={styles.label}>失败{item.failUnits.length}</span>
            <span className={styles.list}>{item.failUnits.join('、')}</span>
          </div>
        </>
      );
    case 7:
      return <>定时申报时间：{moment(item.timelySubmitTime).format('YYYY.MM.DD HH:mm')}</>;
    case 9:
      return <>原定时申报时间：{moment(item.timelySubmitTime).format('YYYY.MM.DD HH:mm')}</>;
  }
  return <div />;
}

function ItemContent({ item, index }) {
  switch (item.type) {
    case 1:
    case 5:
    case 10:
      break;
    case 0:
    case 2:
    case 4:
    case 8:
      return (
        <Table
          className={styles.table}
          dataSource={item.hourOrderInfos}
          rowKey="hourOrder"
          bordered={true}
          locale={tableLocale}
          pagination={false}
        >
          <Column title="时点" align="center" dataIndex="hourOrder" key="hourOrder" />
          <Column
            align="center"
            title="交易方向"
            dataIndex="tradeStrategy"
            key="tradeStrategy"
            render={(text) => {
              switch (text) {
                case TradeStrategy.SELL:
                  return <span>卖出</span>;
                case TradeStrategy.BUY:
                  return <span>买入</span>;
                case TradeStrategy.NOT_DEAL:
                  return <span>不交易</span>;
                case TradeStrategy.NO_STRATEGY:
                  return <span>无策略</span>;
              }
            }}
          />
          <Column
            align="center"
            title="段一申报电量"
            dataIndex="firstSubmitPower"
            key="firstSubmitPower"
            render={(text, record) => {
              switch (record.submitType) {
                case SubmitType.FIXED:
                  return <>{text.toFixed(3)}MWh</>;
                case SubmitType.INSTALLED_CAPACITY:
                  return <>装机容量*{Math.round(text * 100)}%</>;
                case SubmitType.TRADE_LIMIT:
                  return <>交易限额*{Math.round(text * 100)}%</>;
              }
            }}
          />
          <Column
            align="center"
            title="段一申报电价"
            dataIndex="firstPrice"
            key="firstPrice"
            render={(text) => <>{text.toFixed(2)}元/MWh</>}
          />
          <Column
            align="center"
            title="段二申报电量"
            dataIndex="secondSubmitPower"
            key="secondSubmitPower"
            render={(text, record) => {
              switch (record.submitType) {
                case SubmitType.FIXED:
                  return <>{text.toFixed(3)}MWh</>;
                case SubmitType.INSTALLED_CAPACITY:
                  return <>装机容量*{Math.round(text * 100)}%</>;
                case SubmitType.TRADE_LIMIT:
                  return <>交易限额*{Math.round(text * 100)}%</>;
              }
            }}
          />
          <Column
            align="center"
            title="段二申报电价"
            dataIndex="secondPrice"
            key="secondPrice"
            render={(text) => <>{text.toFixed(2)}元/MWh</>}
          />
        </Table>
      );
    case 3:
      return <>{item.units.join('、')}</>;
    case 6:
      return (
        <>
          <div className={styles.successUnits}>
            <span className={styles.label}>成功{item.successUnits.length}</span>
            <span className={styles.list}>{item.successUnits.join('、')}</span>
          </div>
          <div className={styles.failUnits}>
            <span className={styles.label}>失败{item.failUnits.length}</span>
            <span className={styles.list}>{item.failUnits.join('、')}</span>
          </div>
        </>
      );
    case 7:
      return <>定时申报时间：{moment(item.timelySubmitTime).format('YYYY.MM.DD HH:mm')}</>;
    case 9:
      return <>原定时申报时间：{moment(item.timelySubmitTime).format('YYYY.MM.DD HH:mm')}</>;
  }
  return <div />;
}

function OperateLogModal({ tradeSeqId, currentProgramId, market = {} }, ref) {
  React.useImperativeHandle(ref, () => ({
    initHandle,
  }));

  const [operateLogList, setOperateLogList] = useState([]),
    [operateLogTab, setOperateLogTab] = useState(),
    [showOperateLog, setShowOperateLog] = useState(false),
    [loading, setLoading] = useState(false),
    [programList, setProgramList] = useState([]);

  const initHandle = () => {
    setShowOperateLog(true);
    // 获取全部方案列表
    fetchProgramsAll();
    // 操作日志默认选中方案与主页选中方案保持一致
    setOperateLogTab(currentProgramId);
    fetchOperateLogsFunc(currentProgramId);
  };

  const fetchProgramsAll = async () => {
    const res = await fetchPrograms(tradeSeqId, true);
    if (res?.statusCode === HttpCode.SUCCESS) {
      setProgramList(res.data.programList);
    } else {
      TRMessage.error(res?.message || '获取全部方案列表失败');
    }
  };

  async function fetchOperateLogsFunc(tab) {
    setOperateLogTab(tab);
    setLoading(true);
    const res = await fetchOperateLogs(tab);
    setLoading(false);
    if (res?.statusCode === HttpCode.SUCCESS) {
      setOperateLogList(res.data?.operateLogList);
    } else {
      TRMessage.error(res?.message || '获取操作日志列表失败');
    }
  }

  const changeShowDetail = (index) => {
    let data = JSON.parse(JSON.stringify(operateLogList));
    data[index].showDetail = !data[index].showDetail;
    setOperateLogList(data);
  };

  const arrowIcon = (item, index) => {
    switch (item.type) {
      case 1:
      case 5:
      case 10:
        break;
      default:
        return item.showDetail ? (
          <UpSquareOutlined onClick={() => changeShowDetail(index)} className={styles.arrow} />
        ) : (
          <DownSquareOutlined onClick={() => changeShowDetail(index)} className={styles.arrow} />
        );
      // (
      //   // <img
      //   //   className={styles.arrow}
      //   //   src={item.showDetail ? upHide : downShow}
      //   //   onClick={() => changeShowDetail(index)}
      //   // />
      // );
    }
  };

  return (
    <Drawer
      className={styles.operateLogModal}
      title={
        <div className={styles.modalTitle}>
          <img src={operateLogModal} />
          <span className={styles.text}>操作日志</span>
        </div>
      }
      width={612}
      footer={null}
      visible={showOperateLog}
      onClose={() => {
        setShowOperateLog(false);
      }}
    >
      <Tabs activeKey={operateLogTab} onChange={(key) => fetchOperateLogsFunc(key)}>
        {programList.map((item) => {
          return (
            <TabPane
              tab={item.status !== 3 ? item.title : <span className="isDeleted">{item.title}</span>}
              key={item.id}
            />
          );
        })}
      </Tabs>
      <Spin spinning={loading}>
        <div className={styles.content}>
          {operateLogList.map((item, index) => (
            <div className={`${styles.item} ${item.showDetail ? styles.show : ''}`} key={index}>
              <div className={styles.itemHeader}>
                <div className={styles.left}>
                  {index === 0 ? (
                    <div className={styles.firstCircle}>
                      <div />
                    </div>
                  ) : (
                    <div className={styles.circle} />
                  )}
                  <span className={styles.dateTime}>
                    {moment(item.operateTime).format('YYYY.MM.DD HH:mm:ss')}
                  </span>
                  <span className={styles.operateType}>{operateLogType[item.type]}</span>
                  {arrowIcon(item, index)}
                </div>

                <div className={styles.right}>
                  <span className={styles.label}>操作人：</span>
                  <span className={styles.value}>{item.operateUserName}</span>
                </div>
              </div>
              <div className={styles.itemContent}>
                {market.value === 'PHBSD' ? (
                  <SDItemContent index={index} item={item} />
                ) : (
                  <ItemContent index={index} item={item} />
                )}
              </div>
            </div>
          ))}
        </div>
      </Spin>
    </Drawer>
  );
}

export default connect(
  ({ tenDaysCentralizedBidding }) => ({
    tradeSeqId: tenDaysCentralizedBidding.tradeSeqId,
    currentProgramId: tenDaysCentralizedBidding.currentProgramId,
  }),
  null,
  null,
  { forwardRef: true },
)(React.forwardRef(OperateLogModal));
